package com.wxd.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wxd.reggie.common.CustomException;
import com.wxd.reggie.dto.SetmealDto;
import com.wxd.reggie.entity.Setmeal;
import com.wxd.reggie.entity.SetmealDish;
import com.wxd.reggie.mapper.SetmealMapper;
import com.wxd.reggie.service.SetmealDishService;
import com.wxd.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SermealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private SetmealService setmealService;

    @Override
    // 开启事务
    @Transactional
    public void saveMeal(SetmealDto setmealDto) {
        this.save(setmealDto);
        long setmealId = setmealDto.getId();
        List<SetmealDish> setmealDishList = setmealDto.getSetmealDishes();
        setmealDishList = setmealDishList.stream().map(item -> {
            item.setSetmealId(setmealId);
            return item;
        }).collect(Collectors.toList());
        setmealDishService.saveBatch(setmealDishList);
    }

    /**
     * 删除套餐(可以批量)
     *
     * @param ids
     */
    @Override
    public void removeMealWithDish(List<Long> ids) {
        //1. 根据id查询数据
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        lqw.in(Setmeal::getId, ids);
        lqw.eq(Setmeal::getStatus, 1);
        int count = setmealService.count(lqw);
        if (count > 0) {
            throw new CustomException("套餐正在售卖中，不能删除");
        }
        // 先删除套餐数据
        this.removeByIds(ids);
        // 再删除套餐关联的菜品数据
        LambdaQueryWrapper<SetmealDish> lqwDish = new LambdaQueryWrapper<>();
        lqwDish.in(SetmealDish::getSetmealId, ids);
        setmealDishService.remove(lqwDish);
    }
}
